package com.function.service.impl;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.auth.Auth;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.function.constant.WenXinConstant;
import com.function.mapper.WenXinMapper;
import com.function.domin.pojo.WenXin;
import com.function.properties.WenXinProperties;
import com.function.service.WenXinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class WenXinServiceImpl implements WenXinService {

    @Autowired
    private WenXinProperties wenXinProperties;
    @Autowired
    private WenXinMapper wenXinMapper;

    //static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 调用文心一言
     * @return
     */
    @Override
    public String getAnswer(String content) throws Exception{
        //获取access_token
        /*
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=m7n0ZDMynqaHdarxXptpBjOZ&client_secret=0JA0i8Y7rMWhcjSGfcLZzvIoKvBlJiku&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();
        String accesstoken = StringUtils.substringBetween(responseBody, "\"access_token\":\"", "\",\"scope");
        */
        //通过千帆SDK配置apiKey和secretKey
        Qianfan qianfan = new Qianfan(Auth.TYPE_OAUTH, wenXinProperties.getApiKey(), wenXinProperties.getSecretKey());
        // 指定模型
        ChatResponse resp = qianfan.chatCompletion()
                .model("ERNIE-Speed-128K")
                .addMessage(WenXinConstant.WENXIN_ROLE, content)
                .execute();
        //接受结果
        String result = resp.getResult();
        //记录结果
        WenXin wenXin = WenXin.builder()
                .content(content)
                .answer(result)
                .createTime(LocalDateTime.now())
                .build();
        wenXinMapper.insert(wenXin);
        return result;
    }

}
